//
//  PostsTextViewController.m
//  CYWFrame
//
//  Created by Macx on 2017/8/4.
//  Copyright © 2017年 Macx. All rights reserved.
//

#import "PostsTextViewController.h"

#import "TZImagePickerController.h"
#import "SelectImgCollectionViewCell.h"
#import "PostServer.h"
#import "TCVideoRecordViewController.h"
#import "QBImagePickerController.h"
#import "TXVideoLoadingController.h"
#import "TopicViewController.h"

#import <Masonry.h>
#import <MediaPlayer/MediaPlayer.h>

#import "ISRDataHelper.h"
#import "IATConfig.h"
//#import "UIButton+FixMultiClick.h"

@interface PostsTextViewController () <UICollectionViewDataSource, UICollectionViewDelegate, TZImagePickerControllerDelegate, UITextViewDelegate, QBImagePickerControllerDelegate> {
    CGFloat _itemWH;
    CGFloat _margin;
}

@property (nonatomic ,strong) NSMutableArray *photosArray;
@property (nonatomic ,strong) NSMutableArray *assestArray;
@property BOOL isSelectOriginalPhoto;

@property (nonatomic, strong) NSString *qType; // 答案是否收费类型
@property (nonatomic, strong) NSString *qAmount; // 答案收费金额

@property (nonatomic, assign) BOOL isTopic; // 是否存在话题

@end

@implementation PostsTextViewController {
    
    UIView      *_bgView;
    
    UIButton    *_topic;
    UIButton    *_td; // 话题删除
    
//    UITextField    *_topic;
    
    
    UITextView  *_textView;
    UICollectionView *_collectionView;
//    UIImageView *_videoView;
    UIButton *_videoView;
    
    UIImageView *_videoPlay;
    NSRange     _range;
    
    UITextField *_amountTF;
    
    UIButton    *_videoDelete;
    UILabel     *_videoSize;
}



-(void)viewWillAppear:(BOOL)animated
{
    //    NSLog(@"%s",__func__);
    
    [super viewWillAppear:animated];
    
    [self.navigationController setNavigationBarHidden:YES animated:animated];
    [self initRecognizer];
}



-(void)viewWillDisappear:(BOOL)animated
{
    //    NSLog(@"%s",__func__);
    [self.navigationController setNavigationBarHidden:NO animated:animated];
    
    if ([IATConfig sharedInstance].haveView == NO) {
        
        [_iFlySpeechRecognizer cancel];
        [_iFlySpeechRecognizer setDelegate:nil];
        [_iFlySpeechRecognizer setParameter:@"" forKey:[IFlySpeechConstant PARAMS]];
        
        [_pcmRecorder stop];
        _pcmRecorder.delegate = nil;
    }
    else
    {
        [_iflyRecognizerView cancel];
        [_iflyRecognizerView setDelegate:nil];
        [_iflyRecognizerView setParameter:@"" forKey:[IFlySpeechConstant PARAMS]];
    }
    
    
    [super viewWillDisappear:animated];
}



- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [MBProgressHUD hideHUDForView:self.view animated:YES];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(comRecord:)name:@"completeRecord" object:nil];
    
    [self buildUI];
    
}

// 主页tableView是否滚动接收到通知
- (void)comRecord:(NSNotification *)notification {
    self.videoPath = notification.userInfo[@"path"];
    NSLog(@"－－－－－录制完视频返回收到通知------\n = %@", self.videoPath);
    
    NSFileManager* manager = [NSFileManager defaultManager];
    NSInteger ll = [[manager attributesOfItemAtPath:self.videoPath error:nil] fileSize];
    NSLog(@"1 = %ld", ll);
    
    float k = (float)ll / 1024;
    NSLog(@"%.1fk", k);
    
    float m = k / 1024;
    NSLog(@"%.1fm", m);
    
    _videoSize.text = [NSString stringWithFormat:@"当前视频大小为：%.1fM", m];
    
//    _videoView.image = notification.userInfo[@"cover"];
    [_videoView setBackgroundImage:notification.userInfo[@"cover"] forState:UIControlStateNormal];
    _videoPlay.hidden = NO;
    _videoDelete.hidden = NO;
    
}


//移除广播监听。
-(void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"completeRecord" object:nil];
}

#pragma mark ==========构建UI==========
- (void)buildUI {
    
    self.view.backgroundColor = UISeparatedColorRGB;
    
    UIView *navView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 64)];
    [self.view addSubview:navView];
    navView.backgroundColor = UIMainColorRGB;
    
    UIButton *cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:cancelBtn];
    [cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
    cancelBtn.titleLabel.font = kUHSystemFontWithSize(14);
    [cancelBtn setTitleColor:kWhiteColor forState:UIControlStateNormal];
    cancelBtn.frame = CGRectMake(0, 20, 50, 44);
    [cancelBtn addTarget:self action:@selector(cancelPostClick:) forControlEvents:UIControlEventTouchUpInside];
    
    UILabel *titleL = [[UILabel alloc] initWithFrame:CGRectMake(self.view.centerX-50, 20, 100, 44)];
    [self.view addSubview:titleL];
    titleL.textAlignment = NSTextAlignmentCenter;
    titleL.textColor = kWhiteColor;
    titleL.font = kUHSystemFontWithSize(15);
    
    _bgView = [[UIView alloc] init];
    [self.view addSubview:_bgView];
    _bgView.backgroundColor = kWhiteColor;
    
    _textView = [[UITextView alloc] initWithFrame:CGRectMake(SW(40), 0, SCREEN_WIDTH-SW(20), 100)];
    [_bgView addSubview:_textView];
    _textView.font = kUHSystemFontWithSize(14);
    _textView.textColor = kLightGrayColor;
    _textView.delegate = self;
    _textView.text = @"这一刻你的想法……";
    
    UIButton *yuyinBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    yuyinBtn.titleLabel.font = kUHSystemFontWithSize(14);
    [yuyinBtn setBackgroundColor:UIMainColorRGB];
    [yuyinBtn setTitle:@"语音输入" forState:UIControlStateNormal];
    [yuyinBtn setTitleColor:kWhiteColor forState:UIControlStateNormal];
    [yuyinBtn addTarget:self action:@selector(voiceClick:) forControlEvents:UIControlEventTouchUpInside];
    yuyinBtn.frame = CGRectMake(SCREEN_WIDTH-100, 100, 80, 44);
    [_bgView addSubview:yuyinBtn];
    yuyinBtn.hidden = YES;
    
    _topic = [UIButton buttonWithType:UIButtonTypeCustom];
    _topic.titleLabel.font = kUHSystemFontWithSize(14);
    [_topic setTitle:@" 话题" forState:UIControlStateNormal];
    [_topic setImage:IMAGE(@"icon_topic") forState:UIControlStateNormal];
    [_topic setTitleColor:kGrayColor forState:UIControlStateNormal];
    [_topic addTarget:self action:@selector(topicClick:) forControlEvents:UIControlEventTouchUpInside];
    _topic.frame = CGRectMake(10, 100, [LZCTools textSizeWithText:_topic.titleLabel.text font:_topic.titleLabel.font].width+44, 44);
    _topic.hidden = YES;
    [_bgView addSubview:_topic];
    
    _td = [UIButton buttonWithType:UIButtonTypeCustom];
    _td.hidden = YES;
    [_bgView addSubview:_td];
    [_td setImage:IMAGE(@"icon_delete") forState:UIControlStateNormal];
    [_td addTarget:self action:@selector(topicDeleteClick:) forControlEvents:UIControlEventTouchUpInside];
    [_td mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(_topic.mas_right);
        make.centerY.mas_equalTo(_topic);
        make.width.and.height.mas_offset(44);
    }];
    
//    _topic = [[UITextField alloc] initWithFrame:CGRectMake(10, 100, SCREEN_WIDTH-110, 44)];
//    [_bgView addSubview:_topic];
//    _topic.textColor = kGrayColor;
//    [_topic addTarget:self action:@selector(topicClick:)];
//    _topic.placeholder = @" 话题";
//    _topic.font = kUHSystemFontWithSize(14);
    
    if ([self.type isEqualToString:@"1"]) {
        
        
        // 最后添加，层级最上
//        [self.view addSubview:yuyinBtn];
        
        // 构建 UICollectionView
        
        _margin = 3;
        _itemWH = (self.view.bounds.size.width - 2 * _margin - 3) / 2 - _margin;
        UICollectionViewFlowLayout *flowLayOut = [[UICollectionViewFlowLayout alloc] init];
        flowLayOut.itemSize = CGSizeMake((SCREEN_WIDTH - 50)/ 3, (SCREEN_WIDTH - 50)/ 3);
        flowLayOut.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
//        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, _textView.height+_textView.y, SCREEN_WIDTH,  (SCREEN_WIDTH - 50)/3+20) collectionViewLayout:flowLayOut];
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 144, SCREEN_WIDTH,  (SCREEN_WIDTH - 50)/3+20) collectionViewLayout:flowLayOut];
        
        _collectionView.backgroundColor = kWhiteColor;
        
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        
        [_bgView addSubview:_collectionView];
        
        [_collectionView registerClass:[SelectImgCollectionViewCell class] forCellWithReuseIdentifier:@"cell"];
        
        [_bgView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.mas_equalTo(self.view.mas_left);
            make.bottom.mas_equalTo(_collectionView.mas_bottom);
            make.top.mas_equalTo(navView.mas_bottom);
            make.right.mas_equalTo(self.view.mas_right);
        }];

        
        titleL.text = @"图文";
        if (self.goodId) {
            titleL.text = @"商品评价";
        }
        else if (self.questionId) {
            titleL.text = @"发表答案";
            
            // 如果是专家
            if ([[GetUserDefaule(USERINFO) valueForKey:@"role"] integerValue] == 3) {
                
                UIButton *freeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
                [self.view addSubview:freeBtn];
                [freeBtn setTitle:@" 观看付费:" forState:UIControlStateNormal];
                freeBtn.titleLabel.font = kUHSystemFontWithSize(12);
                [freeBtn setTitleColor:kBlackColor forState:UIControlStateNormal];
                [freeBtn setImage:IMAGE(@"login_un_tick") forState:UIControlStateNormal];
                [freeBtn setImage:IMAGE(@"login_tick") forState:UIControlStateSelected];
                CGSize bsize = [LZCTools textSizeWithText:@" 记住密码" font:kUHSystemFontWithSize(13)];
                [freeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.left.offset(10);;
                    make.top.mas_equalTo(_bgView.mas_bottom).offset(10);
                    make.height.offset(bsize.height+5);
                    make.width.offset(bsize.height+bsize.width);
                }];
                [freeBtn addTarget:self action:@selector(freeClick:) forControlEvents:UIControlEventTouchUpInside];
                
                _amountTF = [[UITextField alloc] init];
                [self.view addSubview:_amountTF];
                _amountTF.placeholder = @" 请输入收费金额";
                _amountTF.text = @"";
                _amountTF.font = kUHSystemFontWithSize(12);
//                _amountTF.delegate = self;
                _amountTF.keyboardType = UIKeyboardTypeDecimalPad;
                [_amountTF mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.left.mas_equalTo(freeBtn.mas_right);
                    make.height.offset(bsize.height+5);
                    make.right.offset(0);
                    make.top.mas_equalTo(freeBtn.mas_top);
                }];
            }
            
            self.qType = @"free";
//            self.qAmount = @"";
        }
        

    }
    
    else {
        
        _td.hidden = YES;
        _topic.hidden = YES;
        
        titleL.text = @"视频";
        
//        yuyinBtn.frame = CGRectMake(SCREEN_WIDTH-100, _textView.height+_textView.y+10+SW(3)-10-44, 80, 44);
//        [_bgView addSubview:yuyinBtn];
        
//        _videoView = [[UIImageView alloc] init];
        _videoView = [UIButton buttonWithType:UIButtonTypeCustom];
        [_bgView addSubview:_videoView];
        _videoView.frame = CGRectMake(10, _textView.height+_textView.y+10, SW(3), SW(3));
//        [_videoView addTarget:self action:@selector(videoPlayClick:)];
        [_videoView addTarget:self action:@selector(videoPlayClick:) forControlEvents:UIControlEventTouchUpInside];
        _videoView.contentMode = UIViewContentModeScaleAspectFill;
//        _videoView.image = self.videoCover;
//        _videoView.image = IMAGE(@"btn_add_pic");
        [_videoView setBackgroundImage:IMAGE(@"btn_add_pic") forState:UIControlStateNormal];
        _videoView.clipsToBounds = YES;
        
        _videoPlay = [[UIImageView alloc] init];
        [_videoView addSubview:_videoPlay];
        _videoPlay.image = IMAGE(@"icon_play");
        _videoPlay.hidden = YES;
//        _videoPlay.center = CGPointMake(_videoView.centerX, _videoView.centerY);
//        _videoPlay.bounds = CGRectMake(0, 0, _videoView.width/2, _videoView.height/2);
        _videoPlay.frame = CGRectMake(_videoView.width/4, _videoView.width/4, _videoView.width/2, _videoView.width/2);
        
        _videoDelete = [UIButton buttonWithType:UIButtonTypeCustom];
        [_videoView addSubview:_videoDelete];
        [_videoDelete setImage:IMAGE(@"photo_delete") forState:UIControlStateNormal];
        _videoDelete.frame = CGRectMake(_videoView.width-20, 0, 20, 20);
        _videoDelete.hidden = YES;
        [_videoDelete addTarget:self action:@selector(deleteVideo:) forControlEvents:UIControlEventTouchUpInside];

        UIButton *recordBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [self.view addSubview:recordBtn];
        [recordBtn setTitle:@"选择" forState:UIControlStateNormal];
        recordBtn.titleLabel.font = kUHSystemFontWithSize(14);
        [recordBtn setTitleColor:kWhiteColor forState:UIControlStateNormal];
        recordBtn.frame = CGRectMake(SCREEN_WIDTH-50, 20, 50, 44);
        [recordBtn addTarget:self action:@selector(recordPostClick:) forControlEvents:UIControlEventTouchUpInside];
        recordBtn.hidden = YES;
        
        _videoSize = [[UILabel alloc] initWithFrame:CGRectMake(10, _videoView.y+_videoView.height, SCREEN_WIDTH-20, 40)];
        [_bgView addSubview:_videoSize];
        _videoSize.textColor = kGrayColor;
        _videoSize.font = kUHSystemFontWithSize(14);
        _videoSize.text = @"上传视频不能大于100M";
        
//        _bgView.frame = CGRectMake(0, navView.height, SCREEN_WIDTH, _videoView.y+_videoView.height+10);
    _bgView.frame = CGRectMake(0, navView.height, SCREEN_WIDTH, _videoSize.y+_videoSize.height);
    }
    
    UIButton *sendBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:sendBtn];
    sendBtn.titleLabel.font = kUHSystemFontWithSize(14);
//    sendBtn.frame = CGRectMake(SCREEN_WIDTH-50, 20, 50, 44);
    CGFloat btnHeight = [LZCTools textSizeWithText:@"发布" font:kUHSystemFontWithSize(14)].height+SW(20);
    sendBtn.frame = CGRectMake(0, SCREEN_HEIGHT-btnHeight, SCREEN_WIDTH, btnHeight);
    [sendBtn setBackgroundColor:UIMainColorRGB];
    [sendBtn setTitle:@"发送" forState:UIControlStateNormal];
    [sendBtn setTitleColor:kWhiteColor forState:UIControlStateNormal];
    [sendBtn addTarget:self action:@selector(sendPostClick:) forControlEvents:UIControlEventTouchUpInside];
    
}

- (void)topicClick:(UIButton *)sender {
    
    TopicViewController *topVC = [[TopicViewController alloc] init];
    
    [topVC returnTopic:^(NSDictionary *topic) {
        self.isTopic = YES;
        [_topic setTitle:[NSString stringWithFormat:@" %@", topic[@"name"]] forState:UIControlStateNormal];
        _topic.frame = CGRectMake(10, 100, [LZCTools textSizeWithText:_topic.titleLabel.text font:_topic.titleLabel.font].width+44, 44);
    }];
    
    
    [self.navigationController pushViewController:topVC animated:YES];

    
    
//    [self presentViewController:[[TopicViewController alloc] init] animated:YES completion:nil];
    
}

- (void)topicDeleteClick:(UIButton *)sender {
    self.isTopic = NO;
    [_topic setTitle:@" 话题" forState:UIControlStateNormal];
    _topic.frame = CGRectMake(10, 100, [LZCTools textSizeWithText:_topic.titleLabel.text font:_topic.titleLabel.font].width+44, 44);
}

- (void)freeClick:(UIButton *)sender {
    sender.selected = !sender.isSelected;
    
    if (sender.isSelected == YES) {
        self.qType = @"charge";
    }
    else
        self.qType = @"free";
}



#pragma mark ==========UICollectionView 响应代理============

- (void)checkLocalPhoto{
    TZImagePickerController *imagePicker;
    // 除了发布图文动态9张图片，其他都3张
    if (self.questionId || self.goodId) {
        imagePicker = [[TZImagePickerController alloc] initWithMaxImagesCount:3 delegate:self];
    }
    else {
        imagePicker = [[TZImagePickerController alloc] initWithMaxImagesCount:9 delegate:self];
    }
    [imagePicker setSortAscendingByModificationDate:NO];
    imagePicker.isSelectOriginalPhoto = _isSelectOriginalPhoto;
    imagePicker.selectedAssets = _assestArray;
    imagePicker.allowPickingVideo = NO;
    [self presentViewController:imagePicker animated:YES completion:nil];
    
}

- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto{
    self.photosArray = [NSMutableArray arrayWithArray:photos];
    self.assestArray = [NSMutableArray arrayWithArray:assets];
    _isSelectOriginalPhoto = isSelectOriginalPhoto;
    [_collectionView reloadData];
    
    
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == _photosArray.count) {
        [self checkLocalPhoto];
    }else{
        TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithSelectedAssets:_assestArray selectedPhotos:_photosArray index:indexPath.row];
        imagePickerVc.isSelectOriginalPhoto = _isSelectOriginalPhoto;
        [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
            _photosArray = [NSMutableArray arrayWithArray:photos];
            _assestArray = [NSMutableArray arrayWithArray:assets];
            _isSelectOriginalPhoto = isSelectOriginalPhoto;
            [_collectionView reloadData];
            _collectionView.contentSize = CGSizeMake(0, ((_photosArray.count + 2) / 3 ) * (_margin + _itemWH));
        }];
        [self presentViewController:imagePickerVc animated:YES completion:nil];
    }
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    if (_photosArray.count < 3) {
         _collectionView.frame = CGRectMake(0, 144, SCREEN_WIDTH, (SCREEN_WIDTH - 50)/3+20);
    }
    else if (_photosArray.count < 6) {
         _collectionView.frame = CGRectMake(0, 144, SCREEN_WIDTH, (SCREEN_WIDTH - 50)/3*2+30);
    }
    else
         _collectionView.frame = CGRectMake(0, 144, SCREEN_WIDTH, (SCREEN_WIDTH - 50)/3*3+40);
    
    return _photosArray.count+1;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    SelectImgCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    
    if (indexPath.row == _photosArray.count) {
        cell.imagev.image = [UIImage imageNamed:@"AlbumAddBtn@2x"];
        //        cell.imagev.backgroundColor = [UIColor redColor];
        cell.deleteButton.hidden = YES;
        
    }else{
        cell.imagev.image = _photosArray[indexPath.row];
        cell.deleteButton.hidden = NO;
    }
    cell.deleteButton.tag = 100 + indexPath.row;
    [cell.deleteButton addTarget:self action:@selector(deletePhotos:) forControlEvents:UIControlEventTouchUpInside];
    return cell;
    
}

- (void)deletePhotos:(UIButton *)sender{
    [_photosArray removeObjectAtIndex:sender.tag - 100];
    [_assestArray removeObjectAtIndex:sender.tag - 100];
    [_collectionView performBatchUpdates:^{
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:sender.tag-100 inSection:0];
        [_collectionView deleteItemsAtIndexPaths:@[indexPath]];
    } completion:^(BOOL finished) {
        [_collectionView reloadData];
    }];
}


#pragma mark ===========响应方法==========
// 取消发布
- (void)cancelPostClick:(UIButton *)sender {
//    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"退出此次编辑？" message:nil preferredStyle:UIAlertControllerStyleAlert];
//    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//        
//    }]];
//    [alert addAction:[UIAlertAction actionWithTitle:@"退出" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self dismissViewControllerAnimated:YES completion:nil];
//    }]];
//    [self presentViewController:alert animated:YES completion:nil];
}
// 发布动态
- (void)sendPostClick:(UIButton *)sender {
    
    if ([_textView.text isEqualToString:@"这一刻你的想法……"] || [_textView.text isEqualToString:@""]) {
        [self presentViewController:[LZCTools alertMessage:@"内容不可以为空"] animated:YES completion:nil];
        return;
    }
    
    NSDictionary *qParam;
    if (self.questionId && [[GetUserDefaule(USERINFO) valueForKey:@"role"] integerValue] == 3) {
        self.qAmount = _amountTF.text;
        if ([self.qType isEqualToString:@"charge"]) {
            if ([self.qAmount isEqualToString:@""]) {
                [LZCTools HUDMessage:@"收费金额不可为空" delay:1.5f];
                return;
            }
            qParam = @{@"type":@"charge",
                       @"amount":self.qAmount};
        }
    }
    
    NSString *topic = @"";
    if (![_topic.titleLabel.text isEqualToString:@" 话题"] && self.isTopic) {
        topic = _topic.titleLabel.text;
    }
    
    [PostServer postsImage:self.photosArray video:self.videoPath text:_textView.text goodId:self.goodId questionId:self.questionId questionParam:qParam topic:topic order_id:self.order_id];
}

- (void)recordPostClick:(UIButton *)sender {
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"选择视频" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        QBImagePickerController *imagePickerController = [QBImagePickerController new];
        imagePickerController.delegate = self;
        imagePickerController.mediaType = QBImagePickerMediaTypeVideo;
        imagePickerController.allowsMultipleSelection = NO;
        imagePickerController.showsNumberOfSelectedAssets = NO;
        
//        UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:videoRecord];
        [self presentViewController:imagePickerController animated:YES completion:nil];
        
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"录制视频" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        TCVideoRecordViewController *videoRecord = [TCVideoRecordViewController new];
        videoRecord.isRecord = @"1";
        UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:videoRecord];
        [self presentViewController:nav animated:YES completion:nil];
        
    }]];

    
    
    [self presentViewController:alert animated:YES completion:nil];
    
    
}

- (void)deleteVideo:(UIButton *)btn {
//    _videoView.image = IMAGE(@"btn_add_pic");
    [_videoView setBackgroundImage:IMAGE(@"btn_add_pic") forState:UIControlStateNormal];
    _videoPlay.hidden = YES;
    _videoDelete.hidden = YES;
    _videoSize.text = @"上传视频不能大于100M";
}

// 预览视频
- (void)videoPlayClick:(UIButton *)img {
    
//    if ([_videoDelete.imageView isEqual:IMAGE(@"btn_add_pic")]) {
//        [self recordPostClick:nil];
//    }
    
    NSData *data1 = UIImagePNGRepresentation(img.currentBackgroundImage);
    NSData *data2 = UIImagePNGRepresentation(IMAGE(@"btn_add_pic"));
    if ([data1 isEqual:data2]) {
        NSLog(@"两个UIimage相同");
        [self recordPostClick:nil];
    } else {
        NSLog(@"两个UIImage不一样");
        NSURL * movieurl =[NSURL fileURLWithPath:self.videoPath];
        
        MPMoviePlayerViewController *player = [[MPMoviePlayerViewController alloc] initWithContentURL:movieurl];
        
        [self presentMoviePlayerViewControllerAnimated:player];
    }
}

#pragma mark ===========代理方法==========
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    
//    if ([text isEqualToString:@"\n"]) {
//        [textView resignFirstResponder];
//        return NO;
//    }
    return YES;
}


- (BOOL)textViewShouldBeginEditing:(UITextView *)textView {
    if ([textView.text isEqualToString:@"这一刻你的想法……"]) {
        textView.text = @"";
        textView.textColor = kBlackColor;
    }
    
    return YES;
}

- (void)textViewDidChangeSelection:(UITextView *)textView {
    
    _range = textView.selectedRange;
    NSLog(@"range  %lu", (unsigned long)_range.length);
    NSLog(@"range  %lu", (unsigned long)_range.location);
}



#pragma mark - QBImagePickerControllerDelegate

- (void)qb_imagePickerController:(QBImagePickerController *)imagePickerController didFinishPickingAssets:(NSArray *)assets
{
    NSLog(@"Selected assets:");
    NSLog(@"%@", assets);
    
    [self dismissViewControllerAnimated:YES completion:^ {
        TXVideoLoadingController *loadvc = [[TXVideoLoadingController alloc] init];
        loadvc.composeMode = NO;
        UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:loadvc];
        [self presentViewController:nav animated:YES completion:nil];
        [loadvc exportAssetList:assets];
    }];
}

- (void)qb_imagePickerControllerDidCancel:(QBImagePickerController *)imagePickerController
{
    NSLog(@"Canceled.");
    
    [self dismissViewControllerAnimated:YES completion:NULL];
}



// 懒加载
- (NSMutableArray *)photosArray{
    if (!_photosArray) {
        self.photosArray = [NSMutableArray array];
    }
    return _photosArray;
}

- (NSMutableArray *)assestArray{
    if (!_assestArray) {
        self.assestArray = [NSMutableArray array];
    }
    return _assestArray;
}

#pragma mark ============讯飞

- (void)voiceClick:(UIButton *)btn {
    
    [IATConfig sharedInstance].haveView = YES;
    
    if ([IATConfig sharedInstance].haveView == NO) {
        
        //        [_textView setText:@""];
        
        
        if ([_textView.text isEqualToString:@"这一刻你的想法……"]) {
            _textView.text =@"";
            _textView.textColor = kBlackColor;
        }
        
        
        [_textView resignFirstResponder];
        self.isCanceled = NO;
        self.isStreamRec = NO;
        
        if(_iFlySpeechRecognizer == nil)
        {
            [self initRecognizer];
        }
        
        [_iFlySpeechRecognizer cancel];
        
        //Set microphone as audio source
        [_iFlySpeechRecognizer setParameter:IFLY_AUDIO_SOURCE_MIC forKey:@"audio_source"];
        
        //Set result type
        [_iFlySpeechRecognizer setParameter:@"json" forKey:[IFlySpeechConstant RESULT_TYPE]];
        
        //Set the audio name of saved recording file while is generated in the local storage path of SDK,by default in library/cache.
        [_iFlySpeechRecognizer setParameter:@"asr.pcm" forKey:[IFlySpeechConstant ASR_AUDIO_PATH]];
        
        [_iFlySpeechRecognizer setDelegate:self];
        
        BOOL ret = [_iFlySpeechRecognizer startListening];
        
        if (ret) {
            
        }else{
            //            [_popUpView showText: NSLocalizedString(@"M_ISR_Fail", nil)];//Last session may be not over, recognition not supports concurrent multiplexing.
        }
    }else {
        
        if(_iflyRecognizerView == nil)
        {
            [self initRecognizer ];
        }
        
        //        [_textView setText:@""];
        if ([_textView.text isEqualToString:@"这一刻你的想法……"]) {
            _textView.text =@"";
            _textView.textColor = kBlackColor;
        }
        
        [_textView resignFirstResponder];
        
        //Set microphone as audio source
        [_iflyRecognizerView setParameter:IFLY_AUDIO_SOURCE_MIC forKey:@"audio_source"];
        
        //Set result type
        [_iflyRecognizerView setParameter:@"plain" forKey:[IFlySpeechConstant RESULT_TYPE]];
        
        //Set the audio name of saved recording file while is generated in the local storage path of SDK,by default in library/cache.
        [_iflyRecognizerView setParameter:@"asr.pcm" forKey:[IFlySpeechConstant ASR_AUDIO_PATH]];
        
        BOOL ret = [_iflyRecognizerView start];
        if (ret) {
        }
    }
    
    
}


#pragma mark - IFlySpeechRecognizerDelegate

/**
 volume callback,range from 0 to 30.
 **/
- (void) onVolumeChanged: (int)volume
{
    
}



/**
 Beginning Of Speech
 **/
- (void) onBeginOfSpeech
{
    NSLog(@"onBeginOfSpeech");
}

/**
 End Of Speech
 **/
- (void) onEndOfSpeech
{
    NSLog(@"onEndOfSpeech");
    
    [_pcmRecorder stop];
}


/**
 recognition session completion, which will be invoked no matter whether it exits error.
 error.errorCode =
 0     success
 other fail
 **/
- (void) onError:(IFlySpeechError *) error
{
    NSLog(@"%s",__func__);
    
    if ([IATConfig sharedInstance].haveView == NO ) {
        
        NSString *text ;
        
        if (self.isCanceled) {
            text = NSLocalizedString(@"T_ISR_Cancel", nil);
            
        } else if (error.errorCode == 0 ) {
            if (_result.length == 0) {
                text = NSLocalizedString(@"T_ISR_NoRlt", nil);
            }else {
                text = NSLocalizedString(@"T_ISR_Succ", nil);
                //empty results
                _result = nil;
            }
        }else {
            text = [NSString stringWithFormat:@"Error：%d %@", error.errorCode,error.errorDesc];
            NSLog(@"%@",text);
        }
        
        
    }else {
        NSLog(@"errorCode:%d",[error errorCode]);
    }
    
}

/**
 result callback of recognition without view
 results：recognition results
 isLast：whether or not this is the last result
 **/
- (void) onResults:(NSArray *) results isLast:(BOOL)isLast
{
    NSMutableString *resultString = [[NSMutableString alloc] init];
    NSDictionary *dic = results[0];
    
    for (NSString *key in dic) {
        [resultString appendFormat:@"%@",key];
    }
    
    _result =[NSString stringWithFormat:@"%@%@", _textView.text,resultString];
    NSString * resultFromJson =  [ISRDataHelper stringFromJson:resultString];
    _textView.text = [NSString stringWithFormat:@"%@%@", _textView.text,resultFromJson];
    
    if (isLast){
        NSLog(@"ISR Results(json)：%@",  self.result);
    }
    NSLog(@"_result=%@",_result);
    NSLog(@"resultFromJson=%@",resultFromJson);
    NSLog(@"isLast=%d,_textView.text=%@",isLast,_textView.text);
}

/**
 result callback of recognition with view
 resultArray：recognition results
 isLast：whether or not this is the last result
 **/
- (void)onResult:(NSArray *)resultArray isLast:(BOOL)isLast
{
    NSMutableString *result = [[NSMutableString alloc] init];
    NSDictionary *dic = [resultArray objectAtIndex:0];
    
    for (NSString *key in dic) {
        [result appendFormat:@"%@",key];
    }
    NSLog(@"range  %lu", (unsigned long)_range.location);
    
    // 如果光标小于，就做处理
    if (_range.location < _textView.text.length) {
        
        NSString *str1 = [_textView.text substringToIndex:_range.location];//截取掉下标5之前的字符串
        NSString *str2 = [_textView.text substringFromIndex:_range.location];//截取掉下标3之后的字符串
        _textView.text = [NSString stringWithFormat:@"%@%@%@", str1, result, str2];
    }
    else
        _textView.text = [NSString stringWithFormat:@"%@%@",_textView.text,result];
}



/**
 callback of canceling recognition
 **/
- (void) onCancel
{
    NSLog(@"Recognition is cancelled");
}

-(void) showPopup
{
    //    [_popUpView showText: NSLocalizedString(@"T_ISR_Uping", nil)];
}

#pragma mark - IFlyDataUploaderDelegate

/**
 result callback of uploading contacts or customized words
 **/
- (void) onUploadFinished:(IFlySpeechError *)error
{
    NSLog(@"%d",[error errorCode]);
    
    if ([error errorCode] == 0) {
        //        [_popUpView showText: NSLocalizedString(@"T_ISR_UpSucc", nil)];
    }
    else {
        //        [_popUpView showText: [NSString stringWithFormat:@"%@:%d", NSLocalizedString(@"T_ISR_UpFail", nil), error.errorCode]];
        
    }
    
}


#pragma mark - Initialization

/**
 initialize recognition conctol and set recognition params
 **/
-(void)initRecognizer
{
    NSLog(@"%s",__func__);
    
    if ([IATConfig sharedInstance].haveView == NO) {
        
        //recognition singleton without view
        if (_iFlySpeechRecognizer == nil) {
            _iFlySpeechRecognizer = [IFlySpeechRecognizer sharedInstance];
        }
        
        [_iFlySpeechRecognizer setParameter:@"" forKey:[IFlySpeechConstant PARAMS]];
        
        //set recognition domain
        [_iFlySpeechRecognizer setParameter:@"iat" forKey:[IFlySpeechConstant IFLY_DOMAIN]];
        
        _iFlySpeechRecognizer.delegate = self;
        
        if (_iFlySpeechRecognizer != nil) {
            IATConfig *instance = [IATConfig sharedInstance];
            
            //set timeout of recording
            [_iFlySpeechRecognizer setParameter:instance.speechTimeout forKey:[IFlySpeechConstant SPEECH_TIMEOUT]];
            //set VAD timeout of end of speech(EOS)
            [_iFlySpeechRecognizer setParameter:instance.vadEos forKey:[IFlySpeechConstant VAD_EOS]];
            //set VAD timeout of beginning of speech(BOS)
            [_iFlySpeechRecognizer setParameter:instance.vadBos forKey:[IFlySpeechConstant VAD_BOS]];
            //set network timeout
            [_iFlySpeechRecognizer setParameter:@"20000" forKey:[IFlySpeechConstant NET_TIMEOUT]];
            
            //set sample rate, 16K as a recommended option
            [_iFlySpeechRecognizer setParameter:instance.sampleRate forKey:[IFlySpeechConstant SAMPLE_RATE]];
            
            //set language
            [_iFlySpeechRecognizer setParameter:instance.language forKey:[IFlySpeechConstant LANGUAGE]];
            //set accent
            [_iFlySpeechRecognizer setParameter:instance.accent forKey:[IFlySpeechConstant ACCENT]];
            
            //set whether or not to show punctuation in recognition results
            [_iFlySpeechRecognizer setParameter:instance.dot forKey:[IFlySpeechConstant ASR_PTT]];
            
        }
        
        //Initialize recorder
        if (_pcmRecorder == nil)
        {
            _pcmRecorder = [IFlyPcmRecorder sharedInstance];
        }
        
        _pcmRecorder.delegate = self;
        
        [_pcmRecorder setSample:[IATConfig sharedInstance].sampleRate];
        
        [_pcmRecorder setSaveAudioPath:nil];    //not save the audio file
        
    }else  {
        
        //recognition singleton with view
        if (_iflyRecognizerView == nil) {
            
            _iflyRecognizerView= [[IFlyRecognizerView alloc] initWithCenter:self.view.center];
        }
        
        [_iflyRecognizerView setParameter:@"" forKey:[IFlySpeechConstant PARAMS]];
        
        //set recognition domain
        [_iflyRecognizerView setParameter:@"iat" forKey:[IFlySpeechConstant IFLY_DOMAIN]];
        
        
        _iflyRecognizerView.delegate = self;
        
        if (_iflyRecognizerView != nil) {
            IATConfig *instance = [IATConfig sharedInstance];
            //set timeout of recording
            [_iflyRecognizerView setParameter:instance.speechTimeout forKey:[IFlySpeechConstant SPEECH_TIMEOUT]];
            //set VAD timeout of end of speech(EOS)
            [_iflyRecognizerView setParameter:instance.vadEos forKey:[IFlySpeechConstant VAD_EOS]];
            //set VAD timeout of beginning of speech(BOS)
            [_iflyRecognizerView setParameter:instance.vadBos forKey:[IFlySpeechConstant VAD_BOS]];
            //set network timeout
            [_iflyRecognizerView setParameter:@"20000" forKey:[IFlySpeechConstant NET_TIMEOUT]];
            
            //set sample rate, 16K as a recommended option
            [_iflyRecognizerView setParameter:instance.sampleRate forKey:[IFlySpeechConstant SAMPLE_RATE]];
            
            //set language
            [_iFlySpeechRecognizer setParameter:instance.language forKey:[IFlySpeechConstant LANGUAGE]];
            //set accent
            [_iFlySpeechRecognizer setParameter:instance.accent forKey:[IFlySpeechConstant ACCENT]];
            //set whether or not to show punctuation in recognition results
            [_iflyRecognizerView setParameter:instance.dot forKey:[IFlySpeechConstant ASR_PTT]];
            
        }
    }
}




-(void)setExclusiveTouchForButtons:(UIView *)myView
{
    for (UIView * button in [myView subviews]) {
        if([button isKindOfClass:[UIButton class]])
        {
            [((UIButton *)button) setExclusiveTouch:YES];
        }
        else if ([button isKindOfClass:[UIView class]])
        {
            [self setExclusiveTouchForButtons:button];
        }
    }
}


#pragma mark - IFlyPcmRecorderDelegate

- (void) onIFlyRecorderBuffer: (const void *)buffer bufferSize:(int)size
{
    NSData *audioBuffer = [NSData dataWithBytes:buffer length:size];
    
    int ret = [self.iFlySpeechRecognizer writeAudio:audioBuffer];
    if (!ret)
    {
        [self.iFlySpeechRecognizer stopListening];
    }
}

- (void) onIFlyRecorderError:(IFlyPcmRecorder*)recoder theError:(int) error
{
    
}

//range from 0 to 30
- (void) onIFlyRecorderVolumeChanged:(int) power
{
    //    NSLog(@"%s,power=%d",__func__,power);
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
